package com.hhd.pdf.component.list;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.component.AbstractPdfComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.ParsedFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.Element;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ListComponent extends AbstractPdfComponent {

    @Override
    public String getName() {
        return "list";
    }

    @Override
    public List<Element> doGenElements(GeneratorContext context) {
        VariableContext variableContext = context.getVariableContext();
        String listFormulaString = context.getParsingElement().attributeValue("list");
        List<VariableContext> subContexts = variableContext.subContextByFormula(ParsedFormula.formula(listFormulaString), false);
        if (CommonUtils.isEmpty(subContexts)) return CommonUtils.newList();

        List<Element> res = CommonUtils.newList();

        for (VariableContext subContext : subContexts) {
            org.dom4j.Element parsingElement = context.getParsingElement();
            GeneratorContext runtime = context.runtime(parsingElement);
            runtime.getRuntimeData().setVariableContext(subContext);
            List<Element> elements = genChildren(runtime, parsingElement);
            if (!CommonUtils.isEmpty(elements)) {
                res.addAll(elements);
            }
        }
        return res;
    }
}
